/**
 * Copyright 2016 vip.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * </p>
 **/

package spring.cloud.tasks.api.service.impl;

import org.apache.commons.lang3.StringUtils;
import spring.cloud.tasks.api.domain.ForecastCronResult;
import spring.cloud.tasks.api.service.UtilsService;
import spring.cloud.tasks.api.utils.CronExpression;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author hebelala
 */
public class UtilsServiceImpl implements UtilsService {

    @Override
    public ForecastCronResult checkAndForecastCron(final String cron)
            throws RuntimeException {

        if (StringUtils.isBlank(cron)) {
            throw new RuntimeException("cron不能为空");
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getDefault());
        CronExpression cronExpression = null;
        try {
            cronExpression = new CronExpression(cron);
        } catch (ParseException e) {
            throw new RuntimeException(String.format("cron(%s)格式错误:%s", cron, e.getMessage()));
        }
        cronExpression.setTimeZone(TimeZone.getDefault());
        ForecastCronResult forecastCronResult = new ForecastCronResult();
        forecastCronResult.setCron(cron);
        forecastCronResult.setNextFireTimes(new ArrayList<String>());
        Date now = new Date();
        for (int i = 0; i < 10; i++) {
            Date next = cronExpression.getNextValidTimeAfter(now);
            if (next != null) {
                forecastCronResult.getNextFireTimes().add(dateFormat.format(next));
                now = next;
            }
        }
        if (forecastCronResult.getNextFireTimes().isEmpty()) {
            throw new RuntimeException(String.format("cron(%s)可能描述的是一个过去的时间，将不会被执行", cron));
        }
        return forecastCronResult;
    }


}
